package com.heima.search.service.impl;

import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.heima.common.exception.CustomException;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.search.dtos.UserSearchDto;
import com.heima.model.search.pojos.ApAssociateWords;
import com.heima.search.service.ApAssociateWordsService;
import com.heima.utils.common.Trie;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.lang.ref.SoftReference;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;


/**
 * @author admin
 */
@Service
public class ApAssociateWordsServiceImpl implements ApAssociateWordsService, InitializingBean {

    //软引用:  SoftReference<变量>当内存要溢出前，会先释放所有软引用变量
    public static volatile SoftReference<Trie> associateWordsTrie = null;

    @Resource
    private MongoTemplate mongoTemplate;

    /**
     * @param userSearchDto
     * @return 查询结果
     * @Description 查询联想词
     */

    @Override
    public ResponseResult findAssociate(UserSearchDto userSearchDto) {
        //1. 校验参数
        if (ObjectUtils.isEmpty(userSearchDto) || StringUtils.isBlank(userSearchDto.getSearchWords())) {
            CustomException.custom(AppHttpCodeEnum.PARAM_INVALID);
        }
        //2. 执行查询模糊查询
        List<ApAssociateWords> wordsList = mongoTemplate.find(Query.query(Criteria.where("associateWords")
                .regex(".*" + userSearchDto.getSearchWords() + ".*")), ApAssociateWords.class);
        return ResponseResult.okResult(wordsList);
    }

    /**
     * @param userSearchDto
     * @return
     * @Description 联想词查询优化v2
     */

    @Override
    public ResponseResult findAssociateV2(UserSearchDto userSearchDto) {
        //1 参数检查
        if (ObjectUtils.isEmpty(userSearchDto) || StringUtils.isBlank(userSearchDto.getSearchWords())) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (ObjectUtils.isEmpty(associateWordsTrie) || ObjectUtils.isEmpty(associateWordsTrie.get())) {
            initTrieData();
        }
        Trie trie = associateWordsTrie.get();
        List<String> words = trie.getData(userSearchDto.getSearchWords());
        List<ApAssociateWords> apAssociateWordList = new ArrayList<>();
        if (words != null && words.size() > 0) {
            for (String word : words) {
                ApAssociateWords associateWords = new ApAssociateWords();
                associateWords.setAssociateWords(word);
                apAssociateWordList.add(associateWords);
            }
        }
        return ResponseResult.okResult(apAssociateWordList);
    }


    /**
     * @Description 初始化trie树
     */
    public void initTrieData() {
        Trie trie = new Trie();
        // 查询联想词
        List<ApAssociateWords> associateWords = mongoTemplate.findAll(ApAssociateWords.class);
        if (associateWords.size() > 0) {
            // 将联想词存入到字典树种
            associateWords.stream().map(ApAssociateWords::getAssociateWords).forEach(trie::insert);
        }
        associateWordsTrie = new SoftReference<>(trie);
    }

    /**
     * @throws Exception
     * @Description 设置service初始化后执行方法
     */
    @Override
    public void afterPropertiesSet() throws Exception {
        System.out.println("初始化tree树");
        initTrieData();
    }
}